/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.servlet;

import br.com.foxline.atlasmobile.enums.TipoDocumento;
import br.com.foxline.model.Annex;
import br.com.foxline.model.Coordenada;
import br.com.foxline.model.Imovel;
import br.com.foxline.model.Proprietario;
import br.com.foxline.service.AnnexService;
import br.com.foxline.service.ImovelService;
import br.com.foxline.service.ProprietarioService;
import br.com.foxline.util.Base64;
import br.com.foxline.util.CoordinateConversion;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.primefaces.json.JSONException;
import org.primefaces.json.JSONObject;

/**
 *
 * @author roniere
 */
@WebServlet(name = "receiverUtilMobileServlet", urlPatterns = "/receiverUtilMobileServlet/*")
public class ReceiverUtilMobileServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    @EJB
    private AnnexService annexService;
    @EJB
    private ImovelService imovelDao;
    @EJB
    private ProprietarioService proprietarioService;

    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestData = processRequest(request);
        Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy").create();

        JSONObject jSONObject = null;

        List<Proprietario> proprietarios = null;

        try {
            jSONObject = new JSONObject(requestData);
        } catch (JSONException ex) {
            Logger.getLogger(ReceiverUtilMobileServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {

            if (jSONObject.get("comando") != null) {

                Imovel imovel = gson.fromJson(requestData, Imovel.class);
                imovel.setId(null);

                if (imovel.getProprietarios() != null) {

                    proprietarios = new ArrayList<Proprietario>();

                    for (Proprietario proprietario : imovel.getProprietarios()) {

                        proprietario.setId(null);
                        
                        proprietario.setTipoDocumento(TipoDocumento.CPF);
                       
                        /**
                         * mock, para satisfazer campo de cpf/cnpj do mobile
                         */
                        if(proprietario.getCpf() != null && !proprietario.getCpf().isEmpty() &&
                                proprietario.getCpf().length() == 14){
                            proprietario.setCnpj(proprietario.getCpf());
                            proprietario.setTipoDocumento(TipoDocumento.CNPJ);
                            proprietario.setCpf(null);
                        }
                        
                        if (proprietario.getCpf() != null
                                && !proprietario.getCpf().isEmpty()) {
                            
                            Proprietario p = proprietarioService.existProprietario(TipoDocumento.CPF, 
                                    proprietario.getCpf());

                            if (p != null) {
                                proprietario = p;
                            }
                        }
                        if (proprietario.getCnpj() != null
                                && !proprietario.getCnpj().isEmpty()) {
                            
                            Proprietario p = proprietarioService.existProprietario(TipoDocumento.CNPJ, 
                                    proprietario.getCnpj());

                            if (p != null) {
                                proprietario = p;
                            }
                        }
                        
                        if (proprietario.getId() == null) {
                            proprietarioService.save(proprietario);
                        } else {
                            proprietarioService.update(proprietario);
                        }
                        proprietarios.add(proprietario);
                    }
                }
                if (imovel.getCoordX() != null) {
                    CoordinateConversion cc = new CoordinateConversion();
                    Coordenada c = new Coordenada();
                    //"24 M 212951 9673551"
                    String coord = cc.latLon2UTM(imovel.getCoordX(), imovel.getCoordY());

                    c.setLat(imovel.getCoordX());
                    c.setLog(imovel.getCoordY());
                    c.setConvN("" + coord.split(" ")[2]);
                    c.setConvE(coord.split(" ")[0] + "" + coord.split(" ")[3]);

                    List<Coordenada> coordenadas = new ArrayList<Coordenada>();
                    coordenadas.add(c);
                    imovel.setCoordenadas(coordenadas);
                }
                if (imovel.getDimensoes() != null) {
                    imovel.getDimensoes().setId(null);
                }
                if (imovel.getEnderecoImovel() != null) {
                    imovel.getEnderecoImovel().setId(null);
                }
                if (imovel.getEnderecoCorrespondencia() != null) {
                    imovel.getEnderecoCorrespondencia().setId(null);
                }

                imovel.setProprietarios(proprietarios);
                imovelDao.save(imovel);

                return;
            }

        } catch (JSONException ex) {
            try {

                Annex annex = gson.fromJson(requestData, Annex.class);

                Annex a = annexService.findUUID(annex.getCod());
                System.err.println("Código: " + annex.getCod());
                a.setContent(annex.getContent());
                a.setFileByte(Base64.decode(annex.getContent()));

                annexService.update(a);

            } catch (Exception ex1) {
                Logger.getLogger(ReceiverUtilMobileServlet.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }

    }

    private String processRequest(HttpServletRequest request) {
        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                jb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jb.toString();

    }
}
